import {reactive,ref,computed} from 'vue'
import {defineStore} from 'pinia'
import { useRouter } from 'vue-router'

import {routes} from '../router/staticRoutes'
import { icons } from 'ant-design-vue/es/image/PreviewGroup'
export const useRouterStore = defineStore("router",()=>{

    // 引入路由实例
    const router = useRouter();

    const tabArr = reactive([]) // 标签数据
    const menuArr = reactive([]);// 菜单数据

    

    let activeKey = ref('/desktop')
    const selectKeys=reactive([]);

    function generatRoutes(){
        this.menuArr.splice(0)
        routes.forEach(item=>{
            let menu = createMenuItemFromRoute(item);
            if (menu != null && menu) {
                this.menuArr.push(menu);
            }
        })   
    }
    
    //点击切换路由
    function changeActiveRoute(key){
        router.push(key) 
        addTab(key) 
        changeActiveKey(key)
    }

    

    function addTab(key){
        var title = findTitleByKey(flattenArray(menuArr),key)
        
        if(tabArr.find(item=>item.title === title)){

        }else{
            let obj ={
                title:title,
                content:"我的文档我",
                key
            }
            tabArr.push(obj)
        }
    }
 
    // 改变当前项
    function changeActiveKey(key) {//切换当前Key
    
        if (activeKey.value !== key) {
            activeKey.value = key;
            selectKeys.splice(0);
            selectKeys.push(activeKey.value);
        }
    }

    return {
        routes,
        tabArr,
        menuArr,
        activeKey,
        selectKeys,
        generatRoutes,
        changeActiveRoute,
        changeActiveKey,
      

    } 
})

// 一个函数，将一个路由对象，转换为左侧菜单栏对象
const createMenuItemFromRoute = (route) => {

    if(route.meta.hidden ===true){
        return null
    }
    let obj = {
        key: route.path,
        title: route.meta.title,
        label: route.meta.title,
        icon:route.meta.icon || "PieChartOutlined"
    }  
    let arr = [];
    if (route.children && route.children.length > 0) {
        route.children.forEach(item => {
            let tmpObj = createMenuItemFromRoute(item);   
                arr.push(tmpObj);          
        })
        if (arr.length > 0) {
            obj.children = arr;
        }
    }
    return obj;
}






//数组扁平化
function flattenArray(arr) {
    let result = [];

    arr.forEach(item => {
        result.push(item);
        if (item.children) {
            result = result.concat(flattenArray(item.children));
        }
    });

    return result;
}

function findTitleByKey(flatArray, key) {
    // 查找匹配项
    const item = flatArray.find(item => item.key === key);

    // 返回找到的项的title，如果未找到则返回null
    return item ? item.title : null;
}
